import 'dart:io';
import 'package:aliyun_oss/aliyun_oss.dart';
import 'package:flutter/material.dart';
import 'package:inmotion_pro/http/api_helper.dart';
import 'package:inmotion_pro/http/api_helper_file.dart';

import 'file_util.dart';

enum FileType { video, image }

enum FileDirectory { light, sound, log, avatar, moment, map, afterSale }

class AliyunOSSUtil {
  static AliyunOSSUtil? _instance;

  AliyunOSSUtil._internal() {
    _instance = this;
  }

  factory AliyunOSSUtil() => _instance ?? AliyunOSSUtil._internal();

  static OSSClient? client;

  // 文件上传到阿里云OSS
  Future<String?> uploadFile(
    FileDirectory directory,
    File? file,
  ) async {
    if (file == null) {
      return null;
    }

    if (client == null) {
      await initOSSClient();
    }

    final bytes = await file.readAsBytes();

    // 枚举类型转String
    String directoryName = directory.toString().split('.').last;

    /// 文件上传预检查，获取上传的文件名
    Map<String, dynamic> rsp = await ApiHelper().uploadPreCheck(directoryName,
        FileUtil.getFileName(file.path), bytes.length.toString());
    if (rsp['name'] != null) {
      debugPrint('newname ---- ${rsp['name']}}');
      String fileName = '${rsp['name']}';

      // 设置上传回调（Callback文档：https://help.aliyun.com/document_detail/31989.htm?spm=a2c4g.11186623.0.0.262440c2Kyjow1#reference-b3p-cyw-wdb）
      Map<String, dynamic> callback = {
        'callbackUrl': 'https://api.imscv.net/v1/file/oss/notify',
        'callbackBody': "size=${bytes.length}"
      };
      // 上传回调自定义参数，由Key和Value组成，Key必须以x:开始，且必须小写
      Map<String, dynamic> callbackVar = {
        'x:type': 'typeValue',
        'x:name': fileName,
        'x:mime': 'mimeValue',
        'x:token': 'tokenValue'
      };

      // OSSResponse? response = await client?.postObjectWithBytes(
      //     bytes, 'inmotion-app', fileName, callback, callbackVar);
      OSSResponse? response = await client?.postObjectWithBytes(
          bytes, 'inmotion-app', fileName, callback, callbackVar);
      debugPrint('OSS Response $response');
      if (response?.statusCode == 200) {
        return fileName;
      }
    } else {
      debugPrint('文件上传预检查失败');
    }
    return null;
  }

  Future<void> initOSSClient() async {
    /// 申请阿里云OSS上传STS
    Map<String, dynamic> rsp = await ApiHelper().applySTS();
    client = OSSClient(
      endpoint: 'oss-cn-shenzhen.aliyuncs.com',
      credentialProvider: OSSAuthCredentialProvider.init(
        authServerUrl: 'https://api.imscv.net/v1/file/oss/sts',
        fetcher: (authServerUrl) async {
          return rsp;
        },
      ),
    );
  }
}
